package rs.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class FileUtil {
	
	/**
     * Utility method to read an entire file as a String.
     *
     * @param file
     * @return File as String.
     * @throws IOException
     */
	public static String readFileAsString(File file) throws IOException {
		return readFileAsString(file, "utf8");
	}
	/**
     * Utility method to read an entire file as a String.
     *
     * @param file
     * @param charset CharSet
     * @return File as String.
     * @throws IOException
     */
    public static String readFileAsString(File file, String charset) throws IOException {
    	FileInputStream fis = new FileInputStream(file);
        StringBuffer sb = new StringBuffer((int) file.length());
        BufferedReader br = new BufferedReader(new InputStreamReader(
        		fis, charset));
        try {
        	    String line = br.readLine();
        	    while (line != null) {
        	    	    sb.append(line);
                        sb.append("\n");
        	    	    line = br.readLine();
        	    }
        } finally {
        	    br.close();
        	    fis.close();
        }
        return sb.toString();
    }
	
	public static boolean ifModifySince(File f, long lastModify){
		return f.lastModified() != lastModify;
	}
	
	public static void appendToFile(String str, String filePath){
		File file = new File(filePath);
		//FileOutputStream fos = new FileOutputStream(file, true);
		FileWriter fw = null;
		PrintWriter pw = null;
		try {
			if(!file.exists()){
				file.createNewFile();
			}
			fw = new FileWriter(file, true);
			pw = new PrintWriter(fw);
			pw.println(str);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			pw.close();
		}
		
	}
}
